Lists¶

🎨 Arithmetic Operators¶

In [1]:
7 + 2
Out[1]:
9
In [2]:
7 - 2
Out[2]:
5
In [3]:
7 * 2
Out[3]:
14
In [4]:
7 ** 2
Out[4]:
49

7 ** 2 is $ 7 ^ 2 $

In [5]:
7 / 2
Out[5]:
3.5
In [10]:
7 // 2
Out[10]:
3
In [11]:
7 % 2
Out[11]:
1

$\frac{7}{2} = 3r1$

7 // 2 gives us the $3$

7 % 2 gives us the $1$ (the remainder)

🎨 Comparisons¶

In [12]:
2 > 1
Out[12]:
True
In [13]:
2 > 2
Out[13]:
False
In [15]:
2 <= 2
Out[15]:
True
In [16]:
4 == 4
Out[16]:
True
In [20]:
4 != 6
Out[20]:
True

🎨 []¶

🖌 .append(...)¶

append: to put after, to place at the end

In [25]:
names = []
while True:
    name = input("Give me a name: ")
    if name == 'q':
        break
    names.append(name)
    
print(names)
Give me a name: Hank
Give me a name: Hannah
Give me a name: q
['Hank', 'Hannah']
  • [] creates an empty list
  • .append(...) adds the item to the list
  • you can see the contents by printing the list
    • Note the commas
  • What happens when you enter no names (enter 'q' the first time)?
In [22]:
names = ['Julia', 'Juan', 'George', 'Gina']
print(names)
['Julia', 'Juan', 'George', 'Gina']

You can define a list with initial contents.

In [27]:
names = ['Julia', 'Juan', 'George', 'Gina']
while True:
    name = input("Give me a name: ")
    if name == '':
        break
    names.append(name)
    
print(names)
Give me a name: George
Give me a name: Jorge
Give me a name: 
['Julia', 'Juan', 'George', 'Gina', 'George', 'Jorge']

You can add to a list that started with contents already.

🎨 len¶

In [28]:
fruit = ['apple', 'peach', 'pear', 'açaí']
how_many = len(fruit)
print(how_many)
4

You can find the length, or size, of a list using the len function.

🖌 for¶

In [30]:
students = ['Julia', 'Juan', 'George', 'Gina']
for name in students:
    print(f"Hello {name}. Welcome to CS 110.")
Hello Julia. Welcome to CS 110.
Hello Juan. Welcome to CS 110.
Hello George. Welcome to CS 110.
Hello Gina. Welcome to CS 110.

👨🏻‍🎨 Bullet styles¶

Write a program that:

  1. Asks the user for a series of items
    • The user inputs '' (empty string) when they are done
  2. Print the list of items using the following bullets:
    • *
    • -
    • >

bullet_styles.py¶

👩🏽‍🎨 Big and Small¶

Write a program that queries the user for a list of numbers (one number at a time).

Then ask the user what number to use as the boundary between "big" and "small" numbers.

Print "You have {how_many} numbers"

Then print the small numbers with the heading "These are small:"

Then print the bit numbers with the heading "These are big:"

Number: 8
Number: 10
Number: 30
Number: 2
Number: 65
Number: 42
Number: 13
Number: 77
Number: 
Boundary: 20
You have 8 numbers
These are small:
8
10
2
13
These are big:
30
65
42
77

Key Ideas¶

  • Arithmetic operators
  • Lists!
  • []
  • .append(...)
  • len
  • for